// 云函数入口文件
const cloud = require('wx-server-sdk')
const {
  WXMINIUser,
  WXMINIMessage
} = require('wx-js-utils');

const appId = 'wxa28b2a6715a9f907'; // 小程序 appId
const secret = '5a95d41307be7b6e32f5dad57c7e6c8a'; // 小程序 secret
const template_id = 'PAf1ca3HFyDPItlxO_TOmAUvFZs5gQ_0m4lRoxq0akk';

cloud.init()
const db = cloud.database()
const todos = db.collection('todos')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let wXMINIUser = new WXMINIUser({
    appId,
    secret
  });

  let access_token = await wXMINIUser.getAccessToken();

  const touser = wxContext.OPENID;
  const form_id = event.form_id; 

  let task = await todos.doc(event.taskId).get();

  // 发送模板消息
  let wXMINIMessage = new WXMINIMessage();
  let result = await wXMINIMessage.sendMessage({
    access_token,
    touser,
    form_id,
    template_id,
    data: {
      thing1: {
        value: task.data.title 
      },
      thing7: {
        value: task.data._id
      },
      time5: {
        value: task.data._id
      },
      thing6: {
        value: task.data.location.address
      }
    },
    page: `pages/todoinfo/todoinfo?id={{task.data._id}}` 
  });
  return result;
}